import { View } from '@tarojs/components'
import { useState } from 'react'
import { useAuth } from '../../../hooks/useAuth'
import Taro, { useDidShow } from '@tarojs/taro'
import LoginPop from '../LoginPop'
import './index.scss'

export default function FloatLoginBar() {
  const { login } = useAuth()
  const [show, setShow] = useState(true)
  const [showLoginPop, setShowLoginPop] = useState(false)

  useDidShow(() => {
    const loginState = Taro.getStorageSync('isLoggedIn')
    if (!loginState) setShow(true)
    else setShow(false)
  })

  const handleLoginClick = () => {
    setShowLoginPop(true)
  }

  const handleLoginSuccess = () => {
    login()
    Taro.showToast({ title: '登录成功', icon: 'success' })
    setShow(false)
    setShowLoginPop(false)
  }

  const handleClosePop = () => {
    setShowLoginPop(false)
  }

  const handleClose = () => setShow(false)

  if (!show) return null

  return (
    <>
      <View className='index-float-bar'>
        <View className='float-bar-close' onClick={handleClose}>×</View>
        <View className='float-bar-text'>登录体验更多精彩</View>
        <View className='float-bar-action'>
          <View className='float-bar-btn' onClick={handleLoginClick}>注册 | 登录</View>
        </View>
      </View>
      <LoginPop
        visible={showLoginPop}
        onClose={handleClosePop}
        onLogin={handleLoginSuccess}
      />
    </>
  )
} 